import React, { useEffect, useRef, useState } from 'react';
import { ColFlex } from 'dw-mx-flex';
import { Button, Checkbox,Radio } from 'dw-mx';
import { DateCell, DateToMoment, SelectCell ,BasicEditTable  ,Table} from 'dw-mx-table';
import { Code, Rule } from 'dw-mx-extend';
import Lov from '@/pages/table/Lov';
import { Form} from 'dw-mx';

export default function BasicEditTableDemo() {
    const dataSource = [
        {
            key: '0',
            name: 'Edward King 0',
            age: 32,
            address: 'London, Park Lane no. 0',
            date: '2020/02/09',
            rwzt: '2',
            ywlx: ['1', '2', '3'],
            ksmc: 'search',
            dq: ['1', '2'],
            xb: '2',
        },
        {
            key: '1',
            name: 'Edward King 1',
            age: 32,
            address: 'London, Park Lane no. 1',
            date: '2020/08/09',
            rwzt: '2',
            ywlx: ['1', '2', '3'],
            ksmc: 'search',
            dq: ['2'],
            xb: '2',
        },
    ];

    const selectFilter = (input, option) => {
        if(option.label.includes(input) === true){
            return option
        }
    }


    const columns = [
        {
            title: 'name',
            dataIndex: 'name',
            width: 100,
            editable: true,
            componentType: {
                type: 'Input',
                props: {
                    placeholder: '请输入',
                    required:true,
                    message:'name 是必填项',
                    rule:Rule.ChnEngRule()
                },

            },
        },
        {
            title: 'age',
            dataIndex: 'age',
            width: 100,
            editable: true,
            componentType: {
                type: 'InputNumber',
                props: {
                    min: 1,
                    max: 100,
                },
            },
        },
        {
            title: 'address',
            dataIndex: 'address',
            width: 200,
            editable: true,
            componentType: {
                type: 'Input.TextArea',
                props: {
                    autoSize: true,
                },
            },
        },
        {
            title: 'date',
            dataIndex: 'date',
            width: 150,
            editable: true,
            componentType: {
                type: 'DatePicker',
                props: {
                    format: 'YYYY/MM/DD',
                },
            },
            render: (value, record, index) => {
                return <DateCell value={value} mask={'YYYY/MM/DD'} />;
            },
        },
        {
            title: '任务状态',
            dataIndex: 'rwzt',
            width: 150,
            editable: true,
            componentType: {
                type: 'Select',
                props: {
                    options: Code.JSONCODE([
                        { value: '1', content: '已完成' },
                        { value: '2', content: '未完成' },
                        { value: '3', content: '已作废' },
                    ]),
                    allowClear: true,
                    showSearch:true,
                    optionFilterProp:"children",
                    filterOption:(input, option) => selectFilter(input, option)
                },
            },
            render: (value, record, index) => {
                return (
                    <SelectCell
                        value={value}
                        align={'left'}
                        options={Code.JSONCODE([
                            { value: '1', content: '已完成' },
                            { value: '2', content: '未完成' },
                            { value: '3', content: '已作废' },
                        ])}
                    />
                );
            },
        },
        {
            title: '业务类型',
            dataIndex: 'ywlx',
            width: 150,
            editable: true,
            componentType: {
                type: 'Select',
                props: {
                    options: Code.STRINGCODE('1:计划建立,2:待遇支付,3:缴费管理,4:交易处理,5:交易处理,6:匹配处理,7:计划管理,8:单位管理,9:人员管理,10:考核管理'),
                    allowClear: true,
                    mode: 'multiple',
                },
            },
            render: (value, record, index) => {
                return <SelectCell value={value} align={'left'} options={Code.STRINGCODE('1:计划建立,2:待遇支付,3:缴费管理,4:交易处理,5:交易处理,6:匹配处理,7:计划管理,8:单位管理,9:人员管理,10:考核管理')} />;
            },
        },
        {
            title: '搜索',
            dataIndex: 'ksmc',
            width: 100,
            editable: true,
            componentType: {
                type: 'Search',
                props: {
                    modalprops: {
                        searchmodal: Lov,
                        props: {},
                    },
                    searchprops: {},
                },
            },
        },
        {
            title: '地区',
            dataIndex: 'dq',
            width: 100,
            editable: true,
            componentType: {
                type: 'Checkbox.Group',
                props: {
                    options: Code.STRINGCODE('1:北京,2:上海,3:深圳'),
                    onChange: (e) => console.log(e),
                    required: true,
                    message: '地区 是必填项',
                },
            },
        },
        {
            title: '性别',
            dataIndex: 'xb',
            width: 100,
            editable: true,
            componentType: {
                type: 'Radio.Group',
                props: {
                    options: Code.STRINGCODE('1:男,2:女'),
                    onChange: (e) => console.log(e),
                    required: true,
                    message: '性别是必填项',
                },
            },
        },
    ];

    const table = Table.useTable()

    const [data, setData] = useState(DateToMoment(dataSource, ['date'], 'YYYY/MM/DD'));

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);

    const [count, setCount] = useState(2);

    const validateFieldsRef = useRef();

    const pagination = {
        pageSize:5,
    }

    useEffect(() => {
        setData(DateToMoment(data, ['date'], 'YYYY/MM/DD'));
    }, [data]);

    const rowSelection = {
        selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    table.setNumberConfig(true,100,'NO.');

    //删除
    const handleDelete = () => {
        const tabledata = data;
        const result = tabledata.filter((item) => {
            if (selectedRowKeys.indexOf(item.key) == -1) {
                return item;
            }
        });
        setSelectedRowKeys([]);
        setData(result);
    };

    //新增
    const handleAdd = () => {
        const newData = {
            key: count.toString(),
            name: `Edward King ${count}`,
            age: 32,
            address: `London, Park Lane no. ${count}`,
            date: new Date(),
            rwzt: '1',
            ywlx: ['1', '2', '3'],
            ksmc: 'search',
            dq: ['3'],
            xb: '1',
        };
        const newsource = [...data, newData];
        setCount(count + 1);
        setData(newsource);
    };

    const getTabledata = (tabledata,key,dataIndex) => {
        if(dataIndex === 'name'){
            const data = tabledata;
            const ret = data.map((item,index) => {
                if(key == item.key){
                    item['address'] = data[key].name
                    return item;
                }else{
                    return item;
                }
            })
            setData(ret);
        }else{
            setData(tabledata)
        }

    };


    //校验
    const validate = async () => {
        // @ts-ignore
        const value = await validateFieldsRef.current.tableValidateFields();
        console.log(value)
    }

    const isDivCell = (dataIndex,record) => {
        if(dataIndex != 'age' && record.age === 35){
            return dataIndex;
        }
    }

    const divCell = (form,record,children,editable,modal,componentType,nameIndex,dataIndex,isform,editing,inputRef,restProps,closeModal,openModal,toggleEdit,groupChange,save) =>{
        if(dataIndex === 'xb'){
            const { onChange ,required, message, rule ,...restComponentTypeProps} = componentType.props ? componentType.props : [];
            return <td {...restProps} ref={inputRef}>
                <Form.Item
                    style={{ margin: 0 }}
                    name={nameIndex}
                    rules={
                        ( required === true ?
                            ( message ?
                                ( rule ? [{required:required,message:message},rule] : [{required:required,message:message}] )
                                : [{required:required,message:"此项必填"}])
                            : (rule ? [rule] : []))
                    }
                >
                    <Radio.Group disabled={true} {...restComponentTypeProps} onChange={(value) => groupChange(value,nameIndex,dataIndex)}/>
                </Form.Item>
            </td>
        }else if(dataIndex === 'dq') {
            const { onChange ,required, message, rule ,...restComponentTypeProps} = componentType.props ? componentType.props : [];
            return <td {...restProps}>
                <Form.Item
                    style={{ margin: 0 }}
                    name={nameIndex}
                    rules={
                        ( required === true ?
                            ( message ?
                                ( rule ? [{required:required,message:message},rule] : [{required:required,message:message}] )
                                : [{required:required,message:"此项必填"}])
                            : (rule ? [rule] : []))
                    }
                >
                    <Checkbox.Group disabled={true} {...restComponentTypeProps} onChange={(value) => groupChange(value, nameIndex, dataIndex)}/>
                </Form.Item>
            </td>
        }else{
            return <td {...restProps}>
                <div>
                    {children}
                </div>
            </td>
        }
    }

    const customRow = (key,style,record) => {
        if(record.age == 35){
            return { style: { background: 'pink' } }
        }
    }

    return (
        <ColFlex>
            <div>
                <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>
                    Add a row
                </Button>
                <Button onClick={handleDelete} type="primary" style={{ marginBottom: 16 }}>
                    删除
                </Button>
                <Button onClick={validate} type="primary" style={{ marginBottom: 16 }}>
                    校验
                </Button>
            </div>
            <BasicEditTable
                dataSource={data}
                columns={columns}
                heightAdaptive={true}
                rowSelection={{ ...rowSelection }}
                ref={validateFieldsRef}
                getChildValues={getTabledata}
                isDivCell={isDivCell}
                divCell={divCell}
                customRow={customRow}
                pagination={pagination}
                tableNumber={{isShow:true,title:'NO',width:150,dataIndex:'num'}}
            />
        </ColFlex>
    )
}